package cn.itsource.pethome.org.service.impl;

import cn.itsource.pethome.basic.service.impl.BaseServiceImpl;
import cn.itsource.pethome.org.domain.Department;
import cn.itsource.pethome.org.mapper.DepartmentMapper;
import cn.itsource.pethome.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    @Autowired(required = false)
    private DepartmentMapper departmentMapper;

    @Override
    @Transactional
    public void save(Department department) {
        if (department.getId() == null) {
            departmentMapper.save(department);
        }else{
            this.update(department);
        }
    }

    public void  findTree(List<Department> departments){
        if(departments.size()!=0){
            for (Department department : departments) {
                //通过parentId查询子部门列表
                List<Department> list = departmentMapper.findByParentid(department.getId());
                if(list.size()!=0){
                    //把结果值查询出来后，封装到children中
                    department.setChildren(list);
                    //依次往下查询所有的级别
                    this.findTree(list);
                }
            }
        }
    }
    @Override
    public List<Department> findDepartmentTree() {
        //查询一级和二级部门
        List<Department> departments = departmentMapper.findOneLevelAndTwoLevelDepartments();
        //循环所有的一级部门
        for (Department department : departments) {
            //拿到所有的二级部门
            List<Department> children = department.getChildren();
            //如果子节点长度为0
            if(children.size()==0){
                //我就要设置children为null，否则前端展示的时候就有下一级的图标（但实际是没有下一级的）
                department.setChildren(null);
            }
          //  从二级部门开始，循环迭代查询三级部门，三级部门循环迭代查询四级部门.......依次循环迭代
            this.findTree(children);
        }
        return departments;
    }


}
